var app = getApp();
let systemOrderInterval;
Page({

  data: {
		/* 实时定位信息 */
		lat: '',
		lng: '',
		
	  cdnUrl: '',
	  userInfo: null,
	  
	  /* 地图参数 */
		MapContext: {},
	  latitude: 0,
	  longitude: 0,
		centerLatitude: 34.751901,
		centerLongitude: 113.6663,
	  windowHeight: app.globalData.windowHeight*2,
	  pattern: "map",// 默认订单列表为map地图模式，list为列表模式
	  systemOrder: true, //系统派单弹窗
	  /* 自定义导航栏参数 */
	  loading: false,
	  color: '#FFFFFF',
	  background: '#02B3BA',
	  show: true,
	  animated: false,
	  back: false,
	  title: '抢单',
	  
	  /* 自定义tabbar */
	  list: [
	  	{
	          "pagePath": "/page/index/index",
	          "iconPath": "/images/index.png",
	          "selectedIconPath": "/images/index-selected.png",
	          "text": "抢单"
	      },
	      {
	          "pagePath": "/page/order_list/index",
	          "iconPath": "/images/timetable.png",
	          "selectedIconPath": "/images/timetable-selected.png",
	          "text": "订单"
	      },
	    
	      {
	          "pagePath": "/page/mine/mine",
	          "iconPath": "/images/mine.png",
	          "selectedIconPath": "/images/mine-selected.png",
	          "text": "我的"
	      },
	  ],
	  currentTab: 0,
		
		unassignOrderList: [],
		unassignOrderInterval: ''//定义获取订单的定时器
  },
  /* 获取后台指派单数量*/
  assignList: function(){
    var that = this;
    app.request('/api/timetable.user/assignList', {}, function (data, ret) {
    	if(data>0){
    		that.setData({
    		  systemOrder: false,
    		});
    	}else{
        that.setData({
          systemOrder: true,
        });
      }
    })
  },
	changePattern: function(e){
		var that = this;
		var list_type = e.currentTarget.dataset.pattern;
		if(list_type == that.data.pattern){
			return false;
		}
		that.setData({
			pattern: list_type,
		})
		that.unassignOrderList();
	},
  tabChange(e) {
	  this.setData({
	  	currentTab: e.detail.index
	  })
    wx.removeStorageSync('isRecording');
    wx.removeStorageSync('recordingTime');
  	wx.reLaunch({
  	  url: e.detail.item.pagePath
  	})
  	
  },
	unassignOrderList: function () {
	  var that = this;
	  app.request('/api/timetable.user/unassignOrderList', {}, function (data, ret) {
			if(that.data.unassignOrderList.lenght == data.lenght){
				that.setData({
				  unassignOrderList: data,
				});
			}else{
				if(that.data.pattern=='list'){
					that.setData({
					  unassignOrderList: data,
					});
				}else{
					wx.reLaunch({
					  url: '/page/index/index?pattern='+that.data.pattern
					})
				}
			}
	    
			if(data.length>0){
				that.setData({
					centerLatitude: data[0].latitude,
					centerLongitude: data[0].longitude,
				});
			}else{
				that.setData({
					centerLatitude: that.data.latitude,
					centerLongitude: that.data.longitude,
				});
			}
	  }, function (data, ret) {
	    app.error(ret.msg);
	  });
	},
  /* 地图模式抢单 */
  mapGrabbingOrder: function (e){
		var that = this;
		var currenId = e.detail.markerId;
		var currenOrder =  {};
		that.data.unassignOrderList.forEach(function (item) {
			if(item.id == currenId){
				currenOrder = item;
			}
		})
  	that.grabbingOrder(currenId, currenOrder.distance);
  },
	/* 列表模式抢单 */
	listGrabbingOrder: function(e){
		var that = this;
		var currenId = e.currentTarget.dataset.id;
		var currenOrder =  {};
		that.data.unassignOrderList.forEach(function (item) {
			if(item.id == currenId){
				currenOrder = item;
			}
		})
		that.grabbingOrder(currenId, currenOrder.distance);
	},
	/* 抢单操作 */
	grabbingOrder: function( id, distance){
		var that = this;
		//停止定时器
		clearInterval(that.data.unassignOrderInterval);
		app.request('/api/timetable.user/grabbingOrder', {id:id,distance:distance}, function (data, ret) {
		  app.error(ret.msg);
			setTimeout(function(){
				if(that.data.pattern=='list'){
					that.onShow();
				}else{
					wx.reLaunch({
					  url: '/page/index/index?pattern='+that.data.pattern
					})
				}
			},2000)
		}, function (data, ret) {
		  app.error(ret.msg);
			that.setData({
				/* 抢单失败继续获取订单 */
				unassignOrderInterval: setInterval(function() {
					that.unassignOrderList();
				},10000)//10秒定时器
			});
		});
	},
  onUnload: function() {
    clearInterval(this.data.unassignOrderInterval);
    clearInterval(systemOrderInterval);
  },
	onHide: function(){
		clearInterval(this.data.unassignOrderInterval);
    clearInterval(systemOrderInterval);
	},
  onShow: function () {
		// 获取当前小程序的页面栈
		var that = this;
		/* 前后台实时定位 */
		that.realTimeLocation(that);
		let pages = getCurrentPages();
		// 数组中索引最大的页面--当前页面
		let currentPage = pages[pages.length - 1];
		// 打印出当前页面中的 options
		if(currentPage.options.hasOwnProperty('pattern')===true){
			that.setData({
			  pattern: currentPage.options.pattern,
			});
		}
		if (app.globalData.userInfo) {
      that.getUserInfo();
			that.unassignOrderList();
      that.assignList();
      systemOrderInterval = setInterval(function() {
      	that.assignList();
      },18800)//10秒定时器
			// that.MapContext = wx.createMapContext('myMap');
		  that.setData({ 
		    userInfo: app.globalData.userInfo,
				/* 开启定时器获取订单 */
				unassignOrderInterval: setInterval(function() {
					that.unassignOrderList();
				},10000)//10秒定时器
		  });
		}else{			
			setTimeout(function () {
				if (app.globalData.userInfo) {
					wx.reLaunch({
						url: '/page/index/index'
					});
				}else{
					app.check(function(ret){}, '/page/index/index');
				}
			}, 500)
		}
		setInterval(function(){
			that.updateLocation();
		},39999)
  },
	updateLocation: function(){
		var that = this;
		app.request('/api/timetable.user/updateLocation', {latitude: that.data.lat, longitude: that.data.lng}, function (data, ret) {
			// console.log(ret);
		}, function (data, ret) {
			// console.log(ret);
		});
	},
	/* 实时定位授权 */
	realTimeLocation: function(e){
		var that = this;
		wx.startLocationUpdateBackground({
			success(res) {
				wx.onLocationChange(function(res) {
					that.setData({
						lat: res.latitude,
						lng: res.longitude
					})
				})
			},
			fail(res) {
				wx.getSetting({
					success: function (res) {
						var statu = res.authSetting;
						console.log(statu);
						if (!statu['scope.userLocationBackground']) {
							wx.showModal({
								title: '是否授权当前位置',
								content: '需要获取您的地理位置，请确认授权，否则将无法计算订单距离',
								confirmColor: '#00cd85',
								cancelColor: '#333',
								success: function (tip) {
									if (tip.confirm) {
										wx.openSetting({
											success: function (data) {
												console.log(data);
												if (data.authSetting["scope.userLocationBackground"] === true) {
													that.realTimeLocation(that);
												} else {
													app.error('请选择使用小程序期间和离开小程序后，以免影响接单');
												}
											}
										})
									}
								}
							})
						}
					},
					fail: function (res) {
						app.error('调用授权窗口失败');
					}
				})
			}
		});
	},
	
  /* 获取用户信息*/
  getUserInfo: function(){
    var that = this;
    app.request("/api/timetable.user/userInfo", {}, function (data, ret) {
      // app.success('头像上传成功!');
      app.globalData.userInfo = data.userInfo;
      that.setData({
        userInfo: data.userInfo
      });
      if(!data.userInfo.rider_apply){
      	app.showApply();
      	return false;
      }else{
        if(app.globalData.userInfo.rider_apply.status == 0 || app.globalData.userInfo.rider_apply.status == 2){
          app.showApply();
          return false;
        }
      }
    }, function (data, ret) {
      // app.error(ret.msg);
    });
  }

})